package com.ronan.imserver.controller;

import com.ronan.common.constant.Constants;
import com.ronan.common.pojo.SendMsgReq;
import com.ronan.common.pojo.SendMsgVo;
import com.ronan.common.proto.Message;
import com.ronan.common.protocol.RIMHeader;
import com.ronan.common.protocol.RIMProtocol;
import com.ronan.common.response.Result;
import com.ronan.common.utils.SessionManager;
import com.ronan.imserver.server.RIMServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * FileName    : com.ronan.imserver.controller
 * Description : 消息推送实现
 *
 * @author : ysk
 * @version : 1.0
 * Create Date : 2021/2/26 0:37
 **/
@Slf4j
@RestController
@RequestMapping(value = "/im/server/message")
public class MessageController {

    @Autowired
    private RIMServer rimServer;

    /**
     * 点对点 => 一定有发送者 和 接收者
     * 推送消息
     *
     * @param req 消息
     * @return {@link Result<Boolean>}
     */
    @PostMapping(value = "/v1SendMsg")
    public Result<SendMsgVo> v1SendMsg(@RequestBody SendMsgReq req) {
        SendMsgVo vo = new SendMsgVo();

        // 消息Id
        long msgNo = getMsgNo();
        // 发送时间戳
        long time = System.currentTimeMillis();

        // 1.组装数据包
        RIMProtocol protocol = new RIMProtocol();
        // 包体
        Message message = Message.newBuilder()
                .setFrom(req.getFrom())
                .setOpe(req.getOpe())
                .setTo(req.getTo())
                .setType(req.getType())
                .setBody(req.getBody())
                .build();
        protocol.setBody(message);

        // 包头
        RIMHeader header = new RIMHeader();
        header.setMsgNo(msgNo);
        header.setCommand(Constants.MsgConstant.MESSAGE);
        header.setTimestamp(time);
        header.setLength(message.toByteArray().length);
        protocol.setHeader(header);

        //2.根据ope判断
        if (Constants.OpeConstant.P2P == req.getOpe()) {
            // 点对点消息推送
            rimServer.sendMsg(protocol,SessionManager.get(req.getTo()));
        } else if (Constants.OpeConstant.GROUP == req.getOpe()) {
            // 点对多人消息推送
            SessionManager.getChannels().forEach((s, c) -> {
                // 排除自己
                if (!s.equals(req.getFrom())) {
                    rimServer.sendMsg(protocol, c);
                }
            });
        } else {
            log.warn("Not Found Ope, ope = {}",req.getOpe());
        }

        vo.setMsgNo(msgNo);
        vo.setTimestamp(time);
        return Result.ok(vo);
    }

    /**
     * 随机获取msgNo
     *
     * @return long
     */
    private static long getMsgNo() {
        long time = System.currentTimeMillis();
        Random random = new Random();
        int rand = random.nextInt(999999);
        return time+rand;
    }
}
